import requests
import time



def get_portsecurities_from_file(filename):
    fo = open(filename, 'r+')
    print("file name: %s" % fo.name)

    portsecurities = []
    line = fo.readline()
    while(line):
        # print(line)
        # print(type(line))
        # byteline = line.encode(encoding='utf-8')
        # print(byteline)
        rline = line.rstrip('\n')
        # byteline = rline.encode(encoding='utf-8')
        # print(byteline)
        sg_data = rline.split('\t')
        print(sg_data)
        portsecurities.append(_make_vcfc_sg_dict(sg_data))
        line = fo.readline()
    
    return portsecurities


def get_securityrules_from_file(filename):
    fo = open(filename, 'r+')
    print("file name: %s" % fo.name)

    securityrules = []
    line = fo.readline()
    while(line):
        rline = line.rstrip('\n')
        sgrule_data = rline.split('\t')
        print(sgrule_data)
        securityrules.append(_make_vcfc_sgrule_dict(sgrule_data))
        line = fo.readline()
    
    return securityrules


def _make_vcfc_sg_dict(sg_data):
    vcfc_sg_dict = {
        'id': sg_data[1],
        'name': sg_data[2],
        'ip_mac_binding': True,
        'denyflow_age': '3600',
        'isDefault': False,
        'emtpy_rule_action': 'deny'
    }

    return vcfc_sg_dict


def _make_vcfc_sgrule_dict(sgrule_data):
    vcfc_sgrule_dict = {
        "id": sgrule_data[1],
        "name": '',
        "portsecurity_id": sgrule_data[2],
        "direction": sgrule_data[4],
        "ip_version": sgrule_data[5].strip("IPv"),
        "ipprefix": sgrule_data[9],
        "protocol": sgrule_data[6],
        "portrange_max": sgrule_data[8],
        "portrange_min": sgrule_data[7]
    }

    return vcfc_sgrule_dict


def sync_sg(url, token, portsecurities):
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Auth-Token': token}
    response = requests.get(url=url, headers=headers)

    old_port_sg = get_portsecurities(url, token)

    old_id_set = set([x.id for x in old_port_sg])
    new_id_set = set([x.id for x in portsecurities])

    same_id = new_id_set.intersection(old_id_set)
    
    create_portsg = []
    update_portsg = []
    for item in portsecurities:
        if item[id] not in same_id:
            create_portsg.append[item]
        else:
            update_portsg.append[item]
    
    # deal create security group 
    create_portsecurities = {
        'port_securities': create_portsg
    }
    
    response = requests.post(url, headers, json=create_portsecurities)
    
    if response.json():
        print(response.json())
    
    # deal update security group
    
    return
            

def get_portsecurities(url, token):
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Auth-Token': token}
    response = requests.get(url=url, headers=headers)
    old_port_sg = []

    if response.json():
        print(response.json())
        port_securities = response.json()
        old_port_sg = port_securities['port_securities']
    
    return old_port_sg


def sync_securityrules(url, token, securityrules):
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Auth-Token': token}
    response = requests.get(url=url, headers=headers)

    old_sg_rules = get_securityrules(url, token)

    old_id_set = set([x.id for x in old_sg_rules])
    new_id_set = set([x.id for x in securityrules])

    same_id = new_id_set.intersection(old_id_set)
    
    create_sgrules = []
    update_sgrule = []
    for item in securityrules:
        if item[id] not in same_id:
            create_sgrules.append[item]
        else:
            update_sgrule.append[item]

    # deal create security rules
    create_securityrules = {
        'securityrules': create_sgrules
    }
    
    response = requests.post(url, headers, json=create_securityrules)
    
    if response.json():
        print(response.json())
    
    # deal update security rules


    return


def get_securityrules(url, token):
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Auth-Token': token}
    response = requests.get(url=url, headers=headers)
    old_sg_rules = []

    if response.json():
        print(response.json())
        sg_rules = response.json()
        old_sg_rules = sg_rules['securityrules']
    
    return old_sg_rules

# baseurl = 'http://10.0.46.225:8080/'
baseurl = 'http://100.64.9.6:8080/'


def login(url, data):
    response = requests.post(url=url, json=data)
    print(response.content)
    if response.json():
        return response.json()
    else:
        return None



if __name__ == '__main__':
    # login
    url = baseurl + 'sdn/v2.0/auth'
    # data = {
    #     "login": {
    #         "user": "admin",
    #         "password": "admin123"
    #     }
    # }
    data = {
        "login": {
            "user": "sdn",
            "password": "h3c.com!"
        }
    }

    record = login(url, data)

    if None is record:
        print("Error!!!")
    # get record
    print(record)
    portsecurities = get_portsecurities_from_file('D:\\01Neil\\PycharmProjects\\pythonStudy\\project\\sync_security\\securitygroup.txt')
    portsecurity_url = baseurl + '/vds/1.0/portsecurities'
    sync_sg(portsecurity_url, record['record']['token'], portsecurities)
    securityrules = get_securityrules_from_file('D:\\01Neil\\PycharmProjects\\pythonStudy\\project\\sync_security\\securityrules.txt')
    securityrules_url = baseurl + '/vds/1.0/securityrules'
    sync_securityrules(securityrules_url, record['record']['token'], securityrules)

        
